var extend = require('extend');

module.exports = {
    getParams: function(body) {
        try {
            return JSON.parse(decodeURIComponent(body));
        } catch (e) {
            return {};
        }
    },

    parseParams: function(req) {
        try {
            var params = this.getParams(req.body);
            req.bodyParams = params;
        } catch (e) {
            console.error(e);
        }
    },

    initValidator: function(req) {
        extend(req.params, req.bodyParams);
        extend(req.query, req.bodyParams);
    },

    /**
     * [checkValidationError description]
     * @param  {[type]} errors [description]
     * @return {boolean}        [是否验证成功，true无异常false存在异常]
     */
    checkValidationError: function(errors) {
        if (errors) {
            console.log("\n");
            console.log("========================================");
            console.log("====参数验证异常开始");
            for (var i = 0; i != errors.length; i++) {
                var error = errors[i];
                console.log(">>>>参数" + error.param + ", 当前值:" + error.value);
                console.log("    错误信息:" + error.msg);
            }
            console.log("====参数验证异常结束");
            console.log("========================================");
            return false;
        } else {
            return true;
        }
    },

    formateDate: function(date, format) {
        if(Object.prototype.toString.call(date) === '[object Date]') {
            var o = {
                "M+": date.getMonth() + 1, //month
                "d+": date.getDate(), //day
                "h+": date.getHours(), //hour
                "m+": date.getMinutes(), //minute
                "s+": date.getSeconds(), //second
                "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
                "S": date.getMilliseconds() //millisecond
            };
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1
                        ? o[k]
                        : ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return format;
        } else {
            throw("param date is not type of Date.");
        }
    }

};
